package org.one.disruptor;

import com.lmax.disruptor.RingBuffer;
import lombok.Data;
import org.apache.commons.beanutils.BeanUtils;
import org.one.entity.TranslatorDataWrapper;

/**
 * @Classname : MessageProducer
 * @Description : 生产者
 * @Author : cty
 * @Date 2023/6/11 20:46
 */

@Data
public class MessageProducer {

    private String producerId;

    private final RingBuffer<TranslatorDataWrapper> ringBuffer;

    public MessageProducer(String producerId, RingBuffer<TranslatorDataWrapper> ringBuffer) {
        this.producerId = producerId;
        this.ringBuffer = ringBuffer;
    }

    /**
     * 向队列发布数据
     * @param wrapper 传输数据包装类
     */
    public void setData(TranslatorDataWrapper wrapper) {
        long sequence = ringBuffer.next();
        try {
            TranslatorDataWrapper curWrapper = ringBuffer.get(sequence);
            BeanUtils.copyProperties(curWrapper, wrapper);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            ringBuffer.publish(sequence);
        }
    }
}
